package com.ruangong.GitClient.GitHubAPI;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import okhttp3.*;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class MoMingUtil {

    public static final String REPOSITORY_TEST_JSON = "{\n" +
            "                        \"id\": 12544093,\n" +
            "                        \"node_id\": \"MDEwOlJlcG9zaXRvcnkxMjU0NDA5Mw==\",\n" +
            "                        \"name\": \"Android\",\n" +
            "                        \"full_name\": \"hmkcode/Android\",\n" +
            "                        \"private\": false,\n" +
            "                        \"owner\": {\n" +
            "                            \"login\": \"hmkcode\",\n" +
            "                            \"id\": 3790597,\n" +
            "                            \"node_id\": \"MDQ6VXNlcjM3OTA1OTc=\",\n" +
            "                            \"avatar_url\": \"https://avatars.githubusercontent.com/u/3790597?v=4\",\n" +
            "                            \"gravatar_id\": \"\",\n" +
            "                            \"url\": \"https://api.github.com/users/hmkcode\",\n" +
            "                            \"html_url\": \"https://github.com/hmkcode\",\n" +
            "                            \"followers_url\": \"https://api.github.com/users/hmkcode/followers\",\n" +
            "                            \"following_url\": \"https://api.github.com/users/hmkcode/following{/other_user}\",\n" +
            "                            \"gists_url\": \"https://api.github.com/users/hmkcode/gists{/gist_id}\",\n" +
            "                            \"starred_url\": \"https://api.github.com/users/hmkcode/starred{/owner}{/repo}\",\n" +
            "                            \"subscriptions_url\": \"https://api.github.com/users/hmkcode/subscriptions\",\n" +
            "                            \"organizations_url\": \"https://api.github.com/users/hmkcode/orgs\",\n" +
            "                            \"repos_url\": \"https://api.github.com/users/hmkcode/repos\",\n" +
            "                            \"events_url\": \"https://api.github.com/users/hmkcode/events{/privacy}\",\n" +
            "                            \"received_events_url\": \"https://api.github.com/users/hmkcode/received_events\",\n" +
            "                            \"type\": \"GitHubUser\",\n" +
            "                            \"site_admin\": false\n" +
            "                        },\n" +
            "                        \"html_url\": \"https://github.com/hmkcode/Android\",\n" +
            "                        \"description\": \"Android related examples\",\n" +
            "                        \"fork\": false,\n" +
            "                        \"url\": \"https://api.github.com/repos/hmkcode/Android\",\n" +
            "                        \"forks_url\": \"https://api.github.com/repos/hmkcode/Android/forks\",\n" +
            "                        \"keys_url\": \"https://api.github.com/repos/hmkcode/Android/keys{/key_id}\",\n" +
            "                        \"collaborators_url\": \"https://api.github.com/repos/hmkcode/Android/collaborators{/collaborator}\",\n" +
            "                        \"teams_url\": \"https://api.github.com/repos/hmkcode/Android/teams\",\n" +
            "                        \"hooks_url\": \"https://api.github.com/repos/hmkcode/Android/hooks\",\n" +
            "                        \"issue_events_url\": \"https://api.github.com/repos/hmkcode/Android/issues/events{/number}\",\n" +
            "                        \"events_url\": \"https://api.github.com/repos/hmkcode/Android/events\",\n" +
            "                        \"assignees_url\": \"https://api.github.com/repos/hmkcode/Android/assignees{/user}\",\n" +
            "                        \"branches_url\": \"https://api.github.com/repos/hmkcode/Android/branches{/branch}\",\n" +
            "                        \"tags_url\": \"https://api.github.com/repos/hmkcode/Android/tags\",\n" +
            "                        \"blobs_url\": \"https://api.github.com/repos/hmkcode/Android/git/blobs{/sha}\",\n" +
            "                        \"git_tags_url\": \"https://api.github.com/repos/hmkcode/Android/git/tags{/sha}\",\n" +
            "                        \"git_refs_url\": \"https://api.github.com/repos/hmkcode/Android/git/refs{/sha}\",\n" +
            "                        \"trees_url\": \"https://api.github.com/repos/hmkcode/Android/git/trees{/sha}\",\n" +
            "                        \"statuses_url\": \"https://api.github.com/repos/hmkcode/Android/statuses/{sha}\",\n" +
            "                        \"languages_url\": \"https://api.github.com/repos/hmkcode/Android/languages\",\n" +
            "                        \"stargazers_url\": \"https://api.github.com/repos/hmkcode/Android/stargazers\",\n" +
            "                        \"contributors_url\": \"https://api.github.com/repos/hmkcode/Android/contributors\",\n" +
            "                        \"subscribers_url\": \"https://api.github.com/repos/hmkcode/Android/subscribers\",\n" +
            "                        \"subscription_url\": \"https://api.github.com/repos/hmkcode/Android/subscription\",\n" +
            "                        \"commits_url\": \"https://api.github.com/repos/hmkcode/Android/commits{/sha}\",\n" +
            "                        \"git_commits_url\": \"https://api.github.com/repos/hmkcode/Android/git/commits{/sha}\",\n" +
            "                        \"comments_url\": \"https://api.github.com/repos/hmkcode/Android/comments{/number}\",\n" +
            "                        \"issue_comment_url\": \"https://api.github.com/repos/hmkcode/Android/issues/comments{/number}\",\n" +
            "                        \"contents_url\": \"https://api.github.com/repos/hmkcode/Android/contents/{+path}\",\n" +
            "                        \"compare_url\": \"https://api.github.com/repos/hmkcode/Android/compare/{base}...{head}\",\n" +
            "                        \"merges_url\": \"https://api.github.com/repos/hmkcode/Android/merges\",\n" +
            "                        \"archive_url\": \"https://api.github.com/repos/hmkcode/Android/{archive_format}{/ref}\",\n" +
            "                        \"downloads_url\": \"https://api.github.com/repos/hmkcode/Android/downloads\",\n" +
            "                        \"issues_url\": \"https://api.github.com/repos/hmkcode/Android/issues{/number}\",\n" +
            "                        \"pulls_url\": \"https://api.github.com/repos/hmkcode/Android/pulls{/number}\",\n" +
            "                        \"milestones_url\": \"https://api.github.com/repos/hmkcode/Android/milestones{/number}\",\n" +
            "                        \"notifications_url\": \"https://api.github.com/repos/hmkcode/Android/notifications{?since,all,participating}\",\n" +
            "                        \"labels_url\": \"https://api.github.com/repos/hmkcode/Android/labels{/name}\",\n" +
            "                        \"releases_url\": \"https://api.github.com/repos/hmkcode/Android/releases{/id}\",\n" +
            "                        \"deployments_url\": \"https://api.github.com/repos/hmkcode/Android/deployments\",\n" +
            "                        \"created_at\": \"2013-09-02T16:12:28Z\",\n" +
            "                        \"updated_at\": \"2024-03-22T10:51:56Z\",\n" +
            "                        \"pushed_at\": \"2023-12-24T16:53:32Z\",\n" +
            "                        \"git_url\": \"git://github.com/hmkcode/Android.git\",\n" +
            "                        \"ssh_url\": \"git@github.com:hmkcode/Android.git\",\n" +
            "                        \"clone_url\": \"https://github.com/hmkcode/Android.git\",\n" +
            "                        \"svn_url\": \"https://github.com/hmkcode/Android\",\n" +
            "                        \"homepage\": null,\n" +
            "                        \"size\": 1841,\n" +
            "                        \"stargazers_count\": 3496,\n" +
            "                        \"watchers_count\": 3496,\n" +
            "                        \"language\": \"Java\",\n" +
            "                        \"has_issues\": true,\n" +
            "                        \"has_projects\": true,\n" +
            "                        \"has_downloads\": true,\n" +
            "                        \"has_wiki\": true,\n" +
            "                        \"has_pages\": false,\n" +
            "                        \"has_discussions\": false,\n" +
            "                        \"forks_count\": 3411,\n" +
            "                        \"mirror_url\": null,\n" +
            "                        \"archived\": false,\n" +
            "                        \"disabled\": false,\n" +
            "                        \"open_issues_count\": 70,\n" +
            "                        \"license\": null,\n" +
            "                        \"allow_forking\": true,\n" +
            "                        \"is_template\": false,\n" +
            "                        \"web_commit_signoff_required\": false,\n" +
            "                        \"topics\": [\n" +
            "\n" +
            "                        ],\n" +
            "                        \"visibility\": \"public\",\n" +
            "                        \"forks\": 3411,\n" +
            "                        \"open_issues\": 70,\n" +
            "                        \"watchers\": 3496,\n" +
            "                        \"default_branch\": \"master\",\n" +
            "                        \"score\": 1\n" +
            "                    }";

    /**
     * 创建一个HTTP连接。
     *
     * @param url 要连接的URL对象，不应为null。
     * @return 返回一个{@link HttpURLConnection}对象，代表与指定URL的HTTP连接。
     * @throws IOException 如果无法打开连接或存在其他I/O错误，则抛出此异常。
     */
    public static HttpURLConnection createConnection(URL url) throws IOException {
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setRequestProperty("Accept", "application/vnd.github.v3+json");
        // 添加请求头，GitHubUser-Agent是必需的，可以替换为自己的GitHub用户名
        conn.setRequestProperty("GitHubUser-Agent", "Mozilla/5.0");
        conn.setRequestProperty("Authorization", "token " + GitHubUser.token);
        return conn;
    }

    /**
     * 获取指定URL的内容。
     *
     * @param url 要获取内容的URL字符串。
     * @return 包含URL内容的字符串。
     */
    public static String getRepositoryInfo(String url)throws Exception {
        //https://api.github.com/repos/hmkcode/Android

            URL githubUrl = new URL(url);
            HttpURLConnection conn = createConnection(githubUrl);
//            HttpURLConnection conn = (HttpURLConnection) githubUrl.openConnection();
//            conn.setRequestMethod("GET");
            conn.setRequestProperty("Authorization", "token " + GitHubUser.token);
//            conn.setRequestProperty("Accept", "application/vnd.github.v3+json");
            String jsonResponse = getHttpURLConnectionContent(conn);
            System.out.println(jsonResponse);
            return jsonResponse;


//        return "Error retrieving repository information";

    }

    /**
     * 从{@link HttpURLConnection}对象获取内容。
     *
     * @param conn 与URL的HTTP连接。
     * @return 包含URL内容的字符串。
     * @throws IOException 如果无法打开连接或存在其他I/O错误，则抛出此异常。
     */
    public static String getHttpURLConnectionContent(HttpURLConnection conn) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
//        System.out.println("Output from Server .... \n");
        StringBuilder builder = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            builder.append(line);
        }
        reader.close();

        return builder.toString();
    }

    /**
     * 获取指定所有者和仓库的信息。
     *
     * @param owner 仓库所有者的用户名。
     * @param repo  仓库的名称。
     * @return 包含仓库信息的字符串。
     */
    public static String getRepositoryInfo(String owner, String repo)throws Exception {

        // 构建GitHub API获取特定仓库的URL
        String url = "https://api.github.com/repos/" + owner + "/" + repo;
        return getRepositoryInfo(url);
    }

    /**
     * 根据关键词搜索GitHub仓库。
     *
     * @param keyword 要搜索的关键词。
     * @return 包含搜索结果的字符串。
     */
    public static String searchGitHubRepository(String keyword) throws Exception{

            // 设置搜索关键词
//            String keyword = "Android";
            // 构建GitHub API搜索仓库的URL
            String url = "https://api.github.com/search/repositories?q=" + keyword;

            // 创建URL对象
            URL obj = new URL(url);
            // 打开连接
            HttpURLConnection conn = (HttpURLConnection) obj.openConnection();

            // 设置请求方式为GET
            conn.setRequestMethod("GET");
            // 添加请求头，GitHubUser-Agent是必需的，可以替换为自己的GitHub用户名
            conn.setRequestProperty("GitHubUser-Agent", "Mozilla/5.0");

            // 获取响应码
            int responseCode = conn.getResponseCode();
            System.out.println("Sending 'GET' request to URL : " + url);
            System.out.println("Response Code : " + responseCode);

            return getHttpURLConnectionContent(conn);
//        return "response.toString()";
    }
    /**
     * 格式化JSON字符串。展示JSON字符串的内容。
     *
     * @param jsonString 要格式化的JSON字符串。
     */
    public static void showJson(String jsonString){
        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        Object json = gson.fromJson(jsonString, Object.class);
        String formattedJson = gson.toJson(json);
        System.out.println(formattedJson);
    }
    public static void fetchPrivateRepos(String accessToken) {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url("https://api.github.com/repos/SilverXQI/Silver_Python")
                .header("Authorization", "Bearer " + accessToken)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    String responseBody = response.body().string();
                    System.out.println("Private Repos: " + responseBody);
                } else {
                    System.out.println("Failed to fetch private repos: " + response.code());
                }
            }

            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
            }
        });
    }

}


